package cn.usian.jyzx.product.service.impl;

import cn.usian.jyzx.model.entity.product.Category;
import cn.usian.jyzx.product.mapper.CategoryMapper;
import cn.usian.jyzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 06 12 17 10
 **/
@Service
public class CategoryServiceImpl implements CategoryService {

   @Autowired
   CategoryMapper categoryMapper;

    @Override
    public List<Category> findOneLevel() {
        return categoryMapper.findOneLevel();
    }


    @Override
    public List<Category> findCategoryTree() {
       return  findCategoryTree2();
    }

    /**
     * 方案一：查询多次SQL  优点：层次清晰 缺点：N次IO效率低
     * @return
     */
    public List<Category> findCategoryTree1() {
        //1.先查询出所有的一级分类的集合
        List<Category> oneLevel = categoryMapper.findOneLevel();
        //2.遍历一级分类的集合，得到每一个一级分类
        for (Category category1 : oneLevel) {
            //3.查询出每个一级分类下的二级分类集合
            List<Category> children = categoryMapper.getCategoryListByParentId(category1.getId());
            category1.setChildren(children);
            //4.遍历每个一级分类下的二级分类集合
            for (Category category2 : children) {
                //5.查询出每个二级下的三级分类集合
                List<Category> children2 = categoryMapper.getCategoryListByParentId(category2.getId());
                category2.setChildren(children2);
            }
        }
        return oneLevel;
    }

    public List<Category> findCategoryTree2() {
        //1.先查询出所有的分类集合
        List<Category> categoryList = categoryMapper.findAll();
        //2.过滤出一级分类集合
        List<Category> categoryList1 = categoryList
                .stream()
                .filter(category -> category.getParentId() == 0)
                .collect(Collectors.toList());

        categoryList1.forEach(category1 -> {
            List<Category> children = categoryList
                    .stream()
                    .filter(category -> category.getParentId().equals(category1.getId()))
                    .collect(Collectors.toList());
            category1.setChildren(children);
            children.forEach(
                    category2 -> {
                        List<Category> children2 = categoryList
                                .stream()
                                .filter(category -> category.getParentId().equals(category2.getId()))
                                .collect(Collectors.toList());
                        category2.setChildren(children2);

            });


        });


         return categoryList1;


    }



}
